/*!
 * @file app.js
 * @project MB Consultoria Jurídica
 * @developer Thiago Braga <thibraga06@gmail.com>
 * @designer Ana Lau <contato@analau.com.br>
 * @url www.mbconsultoriajuridica.com.br
 */


var cpf = $('.maskCpf'),
  login = $('#login, #login-header'),
  password = $('#password, #password-header'),
  recovery = $('.password-recovery'),
  entrar = $('#entrar, #entrar-header'),
  sair = $('.logout'),
  signin = $('.form-signin, .form-processos'),
  contact = $('.form-contact'),
  footer = $('.form-footer'),
  anchor = $('a:not([href^="#"], [href^="//"])'),
  links = $('a:not([href^="//"]), button, input[type="submit"]'),
  menu = $('#menu a, #tabs a');


/**
 * @function _dataTable
 * @description Instantiates the dataTables plugin for table elements.
 */
(function _dataTable() {
  var table = $('table:not(.list)');
  table.dataTable();
  var input = $('.dataTables_filter input');
  input.prop('placeholder', 'Pesquisar');
})();


/**
 * @function _chosen
 * @description Instantiates the Chosen plugin for select elements.
 */
(function _chosen() {
  var select = $('select');
  select.chosen({
    allow_single_deselect: true,
    disable_search_threshold: 4,
    no_results_text: "Não foram encontrados resultados"
  });
})();


/**
 * @function _mask
 * @description Instantiates the maskedInput plugin.
 */
(function _mask() {
  cpf.mask('999.999.999-99');
})();


/**
 * @function _tooltip
 * @description Instantiates the Bootstrap Tooltip plugin.
 */
(function _tooltip() {
  var rel = $('[rel="tooltip"]');
  rel.tooltip({
    animation: false,
    container: 'body',
    html: true
  });
})();


/**
 * [ description]
 * @return {[type]} [description]
 */
(function _typeahead() {
  var type = $('.typeahead');
  type.typeahead({
    source: ['Sócio', 'Associado']
  }).blur(validateSelection);
})();


/**
 * @function externalLinks
 * @description Target _blank for all external links.
 */
(function externalLinks() {
  var a = $('a[href^="//"]');
  a.prop('target', '_blank');
})();


/**
 * @function loadJs
 * @description Load JavaScript files asynchronously.
 * @param {Script} [url] URL of JavaScript file to load
 * @param {function} [callback] Execute a callback function when finished load
 */
(function loadJs(url, callback) {
  for (var i = 0; i < url.length; i++) {
    var s = document.createElement('script');
    s.src = url[i];
    s.type = 'text/javascript';
    s.async = true;
    s.readyState ?
      s.onreadystatechange = function () {
        if (s.readyState === 'loaded' || s.readyState === 'complete') {
          s.onreadystatechange = null;
          callback ? callback() : null;
        }
      } :
      s.onload = function () {
        callback ? callback() : null;
      };
    document.body.appendChild(s);
  }
}(['http://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&callback=renderMap',
  'http://www.google-analytics.com/ga.js']));


/**
 * @function navbarHighlight
 * @description Highlight the active page in navbar
 * @param {jQuery} [menu] The jQuery object of navbar
 */
(function navbarHighlight(menu) {
  for (var i = 0; i < menu.length; i++) {
    if (window.location.href.indexOf(menu.eq(i).prop('href')) == 0)
      menu.eq(i).parent().addClass('active');
  }
})(menu);


/**
 * @function setGoogleAnalytics
 * @description Set the Google Analytics account
 * @param {String} [ua] The Google Analytics user account
 */
(function setGoogleAnalytics(ua) {
  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', ua]);
  _gaq.push(['_trackPageview']);
})('UA-38033597-1');


/**
 *
 * @return
 * @todo Implementar source
 */
function validateSelection() {
  var $this = $(this);
  if (source.indexOf($this.val()) === -1)
    alert('Error : element not in list!');
};


/**
 * @function checkCpf
 * @description Check the CPF via ajax.
 */
function checkCpf() {
  var data = { cpf: cpf.val().replace(/[^\d]+/g, '') };
  if (validateCpf(data.cpf)) {
    $.post(base_url('usuarios/ajax_cpf'), data, function (response) {
      if (!response.success) {
        noty({ text: response.message });
        cpf.val('').focus();
      }
    }, 'json');
  } else {
    if (cpf.val() != '') {
      noty({ text: 'CPF inválido.' });
      cpf.val('');
    }
  }
};


/**
 * @function validateCpf
 * @description Valida o CPF passado por parâmetro.
 * @param {String} cpf CPF para validar.
 * @return {Boolean} Resultado da validação.
 */
function validateCpf(cpf) {
  var i, add, digit = 9;
  cpf = cpf.replace(/[^\d]+/g, '');
  if (cpf == '' || cpf.length != 11 || cpf.match(/^(\d)\1*$/g))
    return false;
  while (digit < 11) {
    add = 0;
    for (i = 0; i < digit; i++)
      add += parseInt(cpf.charAt(i)) * ((digit + 1) - i);
    rev = 11 - (add % 11);
    rev == 10 || rev == 11 ? rev = 0 : null;
    if (rev != parseInt(cpf.charAt(digit)))
      return false;
    digit++;
  }
  return true;
};


/**
 * @function maskCpf
 * @description Mask the CPF field.
 * @return {String}
 */
function maskCpf(cpf) {
  return cpf.substring(0, 3)+'.'+cpf.substring(3, 6)+'.'+cpf.substring(6, 9)+'-'+cpf.substring(9, 11);
};


/**
 * @function checkPermission
 * @description
 * @param {type} module
 * @return {type}
 */
function checkPermission(module) {
  var url = module.split('/'),
    last = url.length - 1,
    data = { url: url[last] };
  $.post(base_url('usuarios/ajax_permission'), data, function (response) {}, 'json');
  window.location.href = module;
};


/**
 * @function login
 * @description Faz o login no site via Ajax
 * @param {HTMLElement} [form]
 */
function loginForm(form) {
  var login = form.find('#login, #login-header'),
    password = form.find('#password, #password-header'),
    entrar = form.find('#entrar, #entrar-header');
  if (login.val() == '' || password.val() == '') {
    noty({ text: "Preencha os campos corretamente." });
    login.removeAttr('disabled').focus();
    password.removeAttr('disabled');
    entrar.removeAttr('disabled');
    return false;
  } else {
    var data = {
      login: login.val().replace(/[\.-]/g, ''),
      password: password.val()
    };
    login.prop('disabled', true);
    password.prop('disabled', true);
    entrar.prop('disabled', true);
    $.post(base_url('usuarios/ajax_login'), data, function (response) {
      noty({ text: response.message });
      if (response.success) {
        $.cookie('logged_in', response.cookie_id, { expires: 30 });
        setTimeout(function () {
          window.location.href = base_url('processos');
        }, 1500);
      } else {
        login.val('').focus();
        password.val('');
      }
    }, 'json');
    login.removeAttr('disabled');
    password.removeAttr('disabled');
    entrar.removeAttr('disabled');
  }
};


/**
 * @function logout
 * @description Erase the cookie on logout.
 */
function logout() {
  $.post(base_url('usuarios/ajax_logout'), function (response) {
    $.removeCookie('logged_in');
    window.location.href = base_url();
  }, 'json');
};


/**
 * @function passwordRecovery
 * @description Creates a modal to recover the user password
 */
function passwordRecovery() {
  var _modal = $('#div-modal'),
    header = $('#result-header'),
    body = $('#result-body'),
    footer = $('#result-footer'),
    save = $('#save-modal');
  header.html('Recupere sua senha');
  body.html('<p>Preencha o campo abaixo com seu e-mail para receber o link de recuperação de senha.</p>\n\
    <form class="form-inline" method="post">\n\
      <input id="email-modal" name="email" class="input-xlarge" autofocus type="text" />\n\
      <button id="enviar-modal" class="btn btn-inverse" type="submit">Enviar</button>\n\
    </form>');
  save.hide();
  footer.hide();
  _modal.modal();
};


/**
 * @function recoveryMail
 * @description Sends email via ajax
 */
function recoveryMail(email) {
  if (email.val() == '') {
    noty({ text: 'Preencha corretamente os campos.' });
    email.focus();
  } else {
    var data = { email: email.val() };
    $.post('usuarios/ajax_recovery', data, function (response) {
      if (response.success) {
        var _modal = $('#div-modal');
        noty({ text: response.message });
        _modal.modal('hide');
      }
    }, 'json');
  }
};


/**
 * @function renderMap
 * @description Render the Google Maps API. The default is map_canvas.
 * @param {String} [id] ID of the element to put the map
 */
function renderMap(id) {
  var title = 'MB Consultoria Jurídica',
    lat = -22.47150000,
    lng = -48.9870000,
    markerLat = -22.47236750,
    markerLng = -48.9879270,
    options = {
      center: new google.maps.LatLng(lat, lng),
      disableDefaultUI: true,
      mapTypeId: google.maps.MapTypeId.ROADMAP,
      zoom: 15
    },
    marker = new google.maps.Marker({
      map: new google.maps.Map(document.getElementById(id || 'map_canvas'), options),
      position: new google.maps.LatLng(markerLat, markerLng),
      title: title
    });
};


/**
 * @function sendMail
 * @description Send mail via ajax
 * @param {jQuery} [form] The contact form
 */
function sendMail(event, form) {
  var loading = form.find('.loading');
  loading.show();
  $.post(base_url('contato/ajax_send'), form.serialize(), function (response) {
    noty({ text: response.message, type: response.type });
    loading.hide();
  }, 'json');
};


/* Events */
links.on('click', function (event) {
  event.preventDefault();
});

recovery.on('click', function () {
  passwordRecovery();
});

anchor.on('click', function () {
  var $this = $(this);
  checkPermission($this.prop('href'));
});

entrar.on('click', function () {
  var form = $(this).parents('form');
  loginForm(form);
});

sair.on('click', function () {
  logout();
});

contact.submit(function () {
  var $this = $(this);
  sendMail($this);
});

footer.submit(function () {
  var $this = $(this);
  sendMail($this);
});

/* Dinamic Events */
$(document).on('blur', '.checkCpf', function (event) {
  checkCpf(event);
});

$(document).on('click', '#enviar-modal', function (event) {
  var email = $('#email-modal');
  event.preventDefault();
  recoveryMail(email);
});